//引入扩展组件
Ext.Loader.setConfig({enabled: true});

Ext.Loader.setPath('Ext.ux', '../ExtJS4.2/ux/');

Ext.require([
    'Ext.data.*',
    'Ext.grid.*',
    'Ext.util.*',
    'Ext.tip.QuickTipManager',
    'Ext.ux.data.PagingMemoryProxy',
    'Ext.ux.ProgressBarPager'
]);
var store;
var grid;
//显示年级班级信息
function showGradeClassInfo(){
	var columns = [
                   {header:'编号',dataIndex:'id',hidden: true},
                   {header:'年级',dataIndex:'grade'},
                   {header:'班级',dataIndex:'theClass',renderer:function(value){
                	   return "("+value+")";
                   }},
                   {header:'备注',dataIndex:'remarks'},
                   {header:'创建时间',dataIndex:'createTime',renderer:function(value){
                	   return formatDateTime(value);
                   }},
                   {header:'最后更新时间',dataIndex:'updateTime',renderer:function(value){
                	   return formatDateTime(value);
                   }}
               ];
	
	store = Ext.create("Ext.data.Store",{
    	pageSize:15, //每页显示几条数据  
        proxy:{  
            type:'ajax',  
            url:'/gradeTheClass/showAllInfo',  
            reader:{  
                type:'json',
                totalProperty:'total',  
                root:'data',  
                idProperty:'id'  
            }  
        },  
        fields:[  
           {name:'id'}, //mapping:createTime0 这样的可以指定列显示的位置，0代表第1列，可以随意设置列显示的位置  
           {name:'grade'},  
           {name:'theClass'},  
           {name:'remarks'},
           {name:'createTime'},
           {name:'updateTime'}
        ]  
    });
	
    var sm = Ext.create('Ext.selection.CheckboxModel');
    grid = Ext.create("Ext.grid.Panel",{
    	border: false,
    	autoScroll:true,
    	store: store,
    	selModel: sm,
        columns: columns,
        height:520,
        loadMask:true, //显示遮罩和提示功能,即加载Loading……  
        forceFit:true, //自动填满表格  
        columnLines:false, //列的边框
        rowLines:true, //设置为false则取消行的框线样式
        dockedItems: [{
        	xtype:'toolbar',
        	dock:'top',
        	displayInfo: true,
        	items: [
					{id:'addUser',text: '配置年级班级',iconCls:'Useradd', listeners: {click:function(){showGradeClassConfig();}}},'-',
					{id:'editUser', text: '编辑班级年级',disabled:true,iconCls:'Useredit',listeners: {click:function(){editGradeClassInfo();}}},'-',
					{id:'delUser', text: '删除班级年级',disabled:true,iconCls:'Userdelete',listeners: {click:function(){delGradeClassInfo();}}},'-'
    	        ]
        },{
            xtype: 'pagingtoolbar',
            store: store,   // GridPanel使用相同的数据源
            dock: 'bottom',
            displayInfo: true,
            plugins: Ext.create('Ext.ux.ProgressBarPager'),
            emptyMsg: "没有记录" //没有数据时显示信息
        }]
    });
    //数据排序
    store.sort('grade','asc');
    //加载数据  
    store.load({params:{start:0,limit:15}}); 
    // 表格配置结束
    //监听表格
    grid.getSelectionModel().on({
        selectionchange: function(sm, selections) {
            if (selections.length) {
            	Ext.getCmp('editUser').setDisabled(false);
            	Ext.getCmp('delUser').setDisabled(false);
            } else {
            	Ext.getCmp('editUser').setDisabled(true);
            	Ext.getCmp('delUser').setDisabled(true);
            }
        }
    });
    //表格右键菜单  
    var contextmenu = new Ext.menu.Menu({  
        id:'theContextMenu',  
        items:[{
        	id:'rightAddUser',
            text:'配置年级班级',
            iconCls:'Useradd',
            handler:function(){  
            	showGradeClassConfig();  
            }  
        },{
        	id:'rightEditUser',
            text:'编辑年级班级',
            iconCls:'Useredit',
            handler:function(){  
            	editGradeClassInfo();
            }  
        },{
        	id:'rightDelUser',
            text:'删除年级班级',
            iconCls:'Userdelete',
            handler:function(){  
            	delGradeClassInfo();
            }  
        },{
        	id:'rightRefresh',
			text : '刷新',
			iconCls: "Arrowrefreshsmall",
			handler : function(){
				store.reload();
			}  
		}]  
    });  
    
    grid.on("itemcontextmenu",function(view,record,item,index,e){  
        e.preventDefault();  
        contextmenu.showAt(e.getXY());  
    });
    
    grid.on("itemdblclick",function(grid, row){
    	editGradeClassInfo(); 
    });
    
    var showGCwin = Ext.create('Ext.window.Window', {
		title: "年级班级配置",
		iconCls: "Wrenchorange",
		layout:'fit',
		width: 800,
		height:500,
		closeAction:'hide',
		maximizable: true,
		modal: true,
		plain: true,
		items: [grid]
	});
	
    showGCwin.show();
}
//设置年级班级
function showGradeClassConfig(){
	var formPanel = Ext.create('Ext.form.Panel', {
		 border : false,
		 defaults:{  
	         margin:'10 0 0 10'  
	     }, 
		 defaultType: 'numberfield',
		 items: [{
				fieldLabel: '年级数量',
				name: 'grade',
				baseChars: "123456789",
				//hideTrigger: true, // 隐藏微调按钮
                allowDecimals: false, // 不允许输入小数
                allowBlank:false,
                nanText: "请输入有效的整数",
				inputType: 'grade'
			},{
				fieldLabel: '班级数量',
				name: 'theClass',
				baseChars: "123456789",
				allowBlank:false,
				nanText: "请输入有效的整数",
				allowDecimals: false, // 不允许输入小数
				inputType: 'theClass'
			}
			],
			buttons: [{
				text: '执&nbsp;行',
				handler: function() {
					if(formPanel.form.isValid()) {
						formPanel.form.submit({
							url: '/gradeTheClass/autoGenerate',
							method: 'POST',
							success: function(form, action) {
								Ext.Msg.alert('提示', '执行成功');
								gcConfigwin.hide();
								store.load({params:{start:0,limit:15}}); 
							},
							failure: function(form, action) {
								switch (action.failureType) {
									case Ext.form.Action.CLIENT_INVALID:
										Ext.Msg.alert('执行失败', '数据字段格式错误！');
										break;
									case Ext.form.Action.CONNECT_FAILURE:
										Ext.Msg.alert('执行失败', '连接异常！');
										break;
									case Ext.form.Action.SERVER_INVALID:
									   Ext.Msg.alert('执行失败', action.result.message);
							   }
							},
							waitMsg: '执行中，请稍候...'
						});
					} else {
						Ext.Msg.alert('提示', '请填写完整再执行！');
					}
				}
			},{
				text: '取&nbsp;消',
				handler: function() {
					gcConfigwin.hide();
				}
			}]
	});
    var gcConfigwin = Ext.create('Ext.window.Window', {
		title: "年级班级配置",
		iconCls: "Wrenchorange",
		layout:'fit',
		width: 300,
		height:180,
		closeAction:'hide',
		modal: true,
		plain: true,
		items: [formPanel]
	});
	
    gcConfigwin.show();
}
//编辑年级班级信息
function editGradeClassInfo(){
	var formPanel = Ext.create('Ext.form.Panel', {
		 border : false,
		 defaults:{  
	         margin:'10 0 0 10'  
	     }, 
		 defaultType: 'numberfield',
		 items: [{
				fieldLabel: 'ID',
				name: 'id',
				inputType: 'id',
				hidden:true
			},{
				fieldLabel: '年级',
				name: 'grade',
				baseChars: "123456789",
				//hideTrigger: true, // 隐藏微调按钮
               allowDecimals: false, // 不允许输入小数
               allowBlank:false,
               nanText: "请输入有效的整数",
				inputType: 'grade'
			},{
				fieldLabel: '班级',
				name: 'theClass',
				baseChars: "123456789",
				allowBlank:false,
				nanText: "请输入有效的整数",
				allowDecimals: false, // 不允许输入小数
				inputType: 'theClass'
			},{
				xtype:'textareafield',
				fieldLabel: '修改备注',
				allowBlank:false,
				maxLengthText :'修改时备注必须填写', 
				name: 'remarks',
				inputType: 'remarks'
			}
			],
			buttons: [{
				text: '保&nbsp;存',
				handler: function() {
					if(formPanel.form.isValid()) {
						formPanel.form.submit({
							url: '/gradeTheClass/updateInfo',
							method: 'POST',
							success: function(form, action) {
								Ext.Msg.alert('提示', '修改成功');
								gcConfigwin.hide();
								store.load({params:{start:0,limit:15}}); 
							},
							failure: function(form, action) {
								switch (action.failureType) {
									case Ext.form.Action.CLIENT_INVALID:
										Ext.Msg.alert('修改失败', '数据字段格式错误！');
										break;
									case Ext.form.Action.CONNECT_FAILURE:
										Ext.Msg.alert('修改失败', '连接异常！');
										break;
									case Ext.form.Action.SERVER_INVALID:
									   Ext.Msg.alert('修改失败', action.result.message);
							   }
							},
							waitMsg: '执行中，请稍候...'
						});
					} else {
						Ext.Msg.alert('提示', '请填写完整再提交！');
					}
				}
			},{
				text: '取&nbsp;消',
				handler: function() {
					gcConfigwin.hide();
				}
			}]
	});
	
	var gcConfigwin = Ext.create('Ext.window.Window', {
		title: "编辑年级班级信息",
		iconCls: "Wrenchorange",
		layout:'fit',
		width: 300,
		height:250,
		closeAction:'hide',
		modal: true,
		plain: true,
		items: [formPanel]
	});
	
    gcConfigwin.show();
    var fields = [  
                  {name:'id'}, //mapping:0 这样的可以指定列显示的位置，0代表第1列，可以随意设置列显示的位置  
                  {name:'grade'},  
                  {name:'theClass'},  
                  {name:'remarks'}
                ];
    var rec = grid.getSelectionModel().getLastSelected();
	var id = rec.get('id');
    formPanel.form.load({
		url: '/gradeTheClass/loadGradeClass?id=' + id,
		method:'POST',
		waitMsg : '正在载入数据...',
		reader: Ext.create('Ext.data.JsonReader', {
			 type  : 'json',
			 root  : 'data'
		 },fields),
		success : function(form,action) {},
		failure : function(form,action) {
			Ext.Msg.alert('编辑年级班级信息', '数据读取失败');
			gcConfigwin.hide();
		}
	});
}
//删除年级班级信息
function delGradeClassInfo(){
	var ids = '';
	var showInfos="";
	var rec = grid.getSelectionModel().getSelection();
	for(var i=0; i<rec.length; i++){
		if(i!=rec.length-1){
			ids += rec[i].get('id')+',';
			//theClass
			showInfos+=rec[i].get('grade')+rec[i].get('theClass')+',';
		}else{
			ids += rec[i].get('id');
			showInfos+=rec[i].get('grade')+rec[i].get('theClass');
		}
	}
	
	Ext.Msg.show({
		title:'删除年级班级信息',
		msg: '确认要将（' + showInfos + '）删除？',
		buttons: Ext.Msg.YESNOCANCEL,
		fn: function(btn, text) {
			if(btn == "yes") {
				Ext.Ajax.request({
					url: '/gradeTheClass/delInfo?ids='+ids,
					success: function(response,options) {
						var respText = Ext.JSON.decode(response.responseText);
						if(respText.code != 'OK') {
							Ext.Msg.alert('删除失败', respText.message + "（" + respText.code + "）");
						}else{
							Ext.Msg.alert('删除成功', '（' + showInfos + '）已被删除！');
							store.load({params:{start:0,limit:15}}); 
						}
					},
					failure: function(response,options) {
						Ext.Msg.alert('删除失败', '删除（' + showInfos + '）失败！');
					}
				});
			}
		},
		icon: Ext.MessageBox.QUESTION
	});	
}